package com.ics.cmsadmin.modules.basic.service.impl;

import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.modules.basic.dao.TeacherDao;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.modules.basic.bean.TeacherBean;
import com.ics.cmsadmin.modules.basic.service.TeacherService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * t_teacher
 * Created bylvsw on 2018-14-25 14:09:44.
 */
@Service("newTeacherService")
public class TeacherServiceImpl implements TeacherService {
    @Resource
    private TeacherDao teacherDao;

    @Override
    public TeacherBean queryById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return teacherDao.queryById(id);
    }

    @Override
    public PageResult list(TeacherBean bean, PageBean page) {
        long count = teacherDao.count(bean);
        if (count == 0) {
            return new PageResult();
        }
        page = page == null ? new PageBean() : page;
        List<TeacherBean> teacherBeans = teacherDao.list(bean, page);
        for (TeacherBean teacherBean : teacherBeans) {
            teacherBean.setSubjects(teacherDao.findSubjectsById(teacherBean.getId()));
        }
        return PageResult.getPage(count, teacherBeans);
    }

    @Override
    public boolean insert(TeacherBean bean) {
        if (bean == null) {
            return false;
        }
        return teacherDao.insert(bean) == 1;
    }

    @Override
    public boolean update(String id, TeacherBean bean) {
        if (StringUtils.isBlank(id) || bean == null || queryById(id) == null) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "参数有误");
        }
        return teacherDao.update(id, bean) == 1;
    }

    @Override
    public boolean delete(String id) {
        if (StringUtils.isBlank(id) || queryById(id) == null) {
            throw new CmsException(ApiResultEnum.DELETE_TABLE_ITEM_FAIL, "参数有误");
        }
        return teacherDao.delete(id) == 1;
    }

    @Override
    public List<TeacherBean> findByCourseId(String courseId) {
        PageBean page = new PageBean(1, Integer.MAX_VALUE);
        return teacherDao.list(TeacherBean.builder().courseId(courseId).build(), page);
    }

    @Override
    public TeacherBean teacherDetail(String id) {
        TeacherBean teacherBean = queryById(id);
        if (teacherBean == null) {
            return null;
        }
        List<String> subjects = teacherDao.findSubjectsById(id);
        teacherBean.setSubjects(subjects);
        return teacherBean;
    }
}
